package com.fx.ruankao.service.impl;

import com.fx.ruankao.entity.Role;
import com.fx.ruankao.mapper.RoleMapper;
import com.fx.ruankao.mapper.RolePermissionMapper;
import com.fx.ruankao.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

/**
 * 角色服务实现类
 */
@Service
@Transactional
public class RoleServiceImpl implements RoleService {
    
    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    
    @Override
    public int insert(Role role) {
        // 设置创建时间
        role.setCreateTime(new java.util.Date());
        return roleMapper.insert(role);
    }
    
    @Override
    public int deleteById(Integer id) {
        return roleMapper.deleteById(id != null ? id.longValue() : null);
    }
    
    @Override
    public int update(Role role) {
        return roleMapper.update(role);
    }
    
    @Override
    public Role selectById(Integer id) {
        return roleMapper.selectById(id != null ? id.longValue() : null);
    }
    
    @Override
    public List<Role> selectAll() {
        return roleMapper.selectList(new Role());
    }
    
    @Override
    public Role selectByRoleName(String roleName) {
        return roleMapper.selectByRoleName(roleName);
    }
    
    @Override
    public List<Role> selectByUserId(Integer userId) {
        return roleMapper.selectRolesByUserId(userId != null ? userId.longValue() : null);
    }
    
    @Override
    public int batchDelete(Integer[] ids) {
        // RoleMapper接口中没有batchDelete方法，这里通过循环删除实现
        int count = 0;
        if (ids != null) {
            for (Integer id : ids) {
                count += roleMapper.deleteById(id != null ? id.longValue() : null);
            }
        }
        return count;
    }
    
    @Transactional
    @Override
    public boolean assignPermissions(Integer roleId, Integer[] permissionIds) {
        // 先删除该角色的所有权限
        rolePermissionMapper.deleteByRoleId(roleId.longValue());
        
        // 如果有权限ID，则重新分配权限
        if (permissionIds != null && permissionIds.length > 0) {
            // 创建角色权限关联对象
            List<com.fx.ruankao.entity.RolePermission> rolePermissions = new java.util.ArrayList<>();
            for (Integer permissionId : permissionIds) {
                com.fx.ruankao.entity.RolePermission rolePermission = new com.fx.ruankao.entity.RolePermission();
                rolePermission.setRoleId(roleId.longValue());
                rolePermission.setPermissionId(permissionId.longValue());
                rolePermissions.add(rolePermission);
            }
            // 批量插入
            rolePermissionMapper.batchInsert(rolePermissions);
        }
        
        return true;
    }
    
    @Override
    public int countRoles() {
        return roleMapper.selectCount(new Role());
    }
}